package 图形界面;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
 * @ClassName: Add3
 * @Auther: Drawin
 * @Date: 2021/11/22 23:35
 * @Description:
 */

public class Add3 extends JFrame {
    /*
   编写加法程序
   用匿名内部类实现ActionListener接口，作为=按钮的监听器
    */
    private JTextField txtNumber1=new JTextField(10);
    private JLabel lblFuHao=new JLabel("+");
    private JTextField txtNumber2=new JTextField(10);
    private JButton btnEqual=new JButton("=");
    private JTextField txtSum=new JTextField(10);
    public Add3(){
        setTitle("两个数相加的程序");
        initialize();//单独编写一个initialize方法，免得构造方法里代码太长

    }
    private void initialize(){
        setLayout(new FlowLayout());//设置窗口的布局为FlowLayout
        //把5个组件添加到窗口中；
        add(txtNumber1);
        add(lblFuHao);
        add(txtNumber2);
        add(btnEqual);
        add(txtSum);
        //窗口组装完毕，下面开始处理事件
        //用匿名内部类实现了ActionLIstener接口
        //注册为btnEqual的ActionEvent事件的监听器
        btnEqual.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    if (txtNumber1.getText().trim().equals("") || txtNumber2.getText().trim().equals("")) {
                        JOptionPane.showMessageDialog(Add3.this,
                                "加数和被加数都不能为空", "提示信息", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                    double a, b, sum;
                    try {
                        a = Double.valueOf(txtNumber1.getText());
                        b = Double.valueOf(txtNumber2.getText());
                        sum = a + b;
                        txtSum.setText(String.valueOf(sum));

                    } catch (Exception ee) {
                        JOptionPane.showMessageDialog(Add3.this, "加数和被加数都必须是数字"
                                , "提示信息", JOptionPane.INFORMATION_MESSAGE);
                        return;
                    }
                }
            });
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        Add3 add = new Add3();
        add.setSize(500,100);
        add.setVisible(true);
        add.setLocationRelativeTo(null);//该代码能够让窗口居中
    }
}

